<?php


namespace api\user\controller;

use cmf\controller\RestBaseController;
use think\Db;
use think\Validate;
use api\common\service\Apibase;
use api\common\service\InviteRule;

class CdkeyController extends RestBaseController
{
    public function list()
    {
        $userId = $this->getUserId();
        $where = array();
        $where['uid'] = $userId;
        $keyList = Db::name("cdkey_logs")->where($where)->order('id desc')->select();
        if ($keyList) {
            $keyList = $keyList->toArray();
        }
        $this->success('success', $keyList);
    }

    public function dllist()
    {
        $userId = $this->getUserId();
        $where = array();
        $where['uuid'] = $userId;
        $keyList = Db::name("cdkey")->where($where)->order('id desc')->select();
        if ($keyList) {
            $keyList = $keyList->toArray();
            foreach ($keyList as $k=>$v){
                $www['keys'] = $v['keys'];
                $log = Db::name("cdkey_logs")->where($www)->find();
                if($log){
                    $keyList[$k]['lingqu'] = 1;
                    $keyList[$k]['used'] = $log['used'];
                    $keyList[$k]['qrobot_id'] = $log['qrobot_id'];
                    $keyList[$k]['uid'] = $log['uid'];
                }else{
                    $keyList[$k]['lingqu'] = 0;
                    $keyList[$k]['used'] = 0;
                    $keyList[$k]['qrobot_id'] = 0;
                    $keyList[$k]['uid'] = 0;
                }
            }
        }
        $this->success('success', $keyList);
    }

    public function add(){
        $userId = $this->getUserId();
        $validate = new Validate([
            'password'     => 'require',
        ]);

        $validate->message([
            'password.require'  => '支付密码必须填写',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        $check_pay = Apibase::check_pay_password($data['password'], $userId);
        if ($check_pay[0] == 0) {
            $this->error($check_pay[1]);
        }
        $num    = $this->request->param('num', 0, 'intval');
        if ($num < 1) {
            $this->error('数量不正确');
        }
        $www['uuid'] = $userId;
        $user = $this->user;
        $old_num = Db::name('cdkey')->where($www)->count();
        if($num + $old_num >= $user['cdkey_num'] || $user['cdkey_num'] <= 0){
            $this->error('超过最大生成数量');
        }
        $memo    = $this->request->param('memo','');
        $data = array();
        for ($i = 0; $i < $num; $i++) {
            $item = array();
            $item['keys'] = $this->getRandomStr(8, false);
            $item['memo'] = $memo;
            $item['selled'] = 0;
            $item['ctime'] = time();
            $item['status'] = 1;
            $item['uuid'] = $userId;
            $data[] = $item;
        }

        //var_dump($data);
        $result    = Db::name('cdkey')->insertAll($data);
        if ($result === false) {
//            $this->error(Db::name('cdkey')->getError());
            $this->error('添加失败！');
        }

        $this->success("添加成功！");
    }

    /**
     * 获得随机字符串
     * @param $len             需要的长度
     * @param $special        是否需要特殊符号
     * @return string       返回随机字符串
     */
    private function getRandomStr($len, $special = true)
    {
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
        );

        if ($special) {
            $chars = array_merge($chars, array(
                "!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
                "%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
                "}", "<", ">", "~", "+", "=", ",", "."
            ));
        }

        $charsLen = count($chars) - 1;
        shuffle($chars);                            //打乱数组顺序
        $str = '';
        for ($i = 0; $i < $len; $i++) {
            $str .= $chars[mt_rand(0, $charsLen)];    //随机取出一位
        }
        $is_have = Db::name('cdkey')->where('keys',$str)->find();
        if($is_have){
            $str = $this->getRandomStr(8, false);
        }
        return $str;
    }

    public function buy()
    {
        $userId = $this->getUserId();


        $validate = new Validate([
            'password'     => 'require',
        ]);

        $validate->message([
            'password.require'  => '支付密码必须填写',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        $check_pay = Apibase::check_pay_password($data['password'], $userId);
        if ($check_pay[0] == 0) {
            $this->error($check_pay[1]);
        }

        $app_conf = cmf_get_option('app_config');
        $amount = floatval($app_conf['cdkey_price']);

        $coin_symbol = 'USDT';
        //查询用户对应币种余额
        $cloud_wallet = Db::name("Wallet")->where(['uid' => $userId, 'coin_symbol' => $coin_symbol, 'type' => 1])->field('id,coin_symbol,cloud_balance,address')->find();
        if (empty($cloud_wallet)) {
            $this->error("查询不到云端钱包账户信息，请稍后重试");
        }
        $cloud_balance = $cloud_wallet['cloud_balance'];
        if ($amount > $cloud_balance) {
            $this->error("钱包账户{$coin_symbol}余额不足");
        }
        Db::startTrans();

        $temp = [
            'cloud_balance' => Db::raw("cloud_balance-" . $amount)
        ];
        $set = Db::name("Wallet")->where(['id' => $cloud_wallet['id']])->update($temp);

        if ($set > 0) {

            $transfer_log = [
                'uid' => $userId,
                'type' => 3,  //3 购买激活码
                'wallet_type' => 1,
                'related_id' => 0,
                'wallet_id' => $cloud_wallet['id'],
                'coin_symbol' => $coin_symbol,
                'from_address' => $cloud_wallet['address'],
                'to_address' => 'cdkey',
                'amount' => 0 - $amount,
                'amount_before' => $cloud_balance,
                'amount_after' => $cloud_balance - $amount,
                'fee' => 0,
                'log_time' => time(),
                'tx_id' => '',
                'memo' => '购买激活码',
                'transfer_status' => 1,
            ];

            $log_id = intval(Db::name("TransferLog")->insertGetId($transfer_log));

            if ($log_id < 1) {
                Db::rollback();
                $this->error("资金账户记录写入失败,请稍后重试");
            }

            $find_cdkey = Db::name("cdkey")->where(array('status' => 1, 'selled' => 0,'uuid'=>0))->find();
            if (!$find_cdkey) {
                Db::rollback();
                $this->error("系统当前无可售激活码,请稍后再来吧");
            }
            $update_info = array('selled' => 1, 'sell_time' => time(), 'uid' => $userId, 'username' => $this->user['mobile'] ? $this->user['mobile'] : $this->user['user_email'], 'price' => $amount, 'coin_symbol' => $coin_symbol);
            $update = Db::name("cdkey")->where('id', $find_cdkey['id'])->update($update_info);
            if (!$update) {
                Db::rollback();
                $this->error("购买激活码失败,请稍后重试#1");
            }
            $insert_info = array('keys' =>  $find_cdkey['keys'], 'ctime' => time(), 'uid' => $userId, 'used' => 0, 'qrobot_id' => 0);
            $ret = Db::name("cdkey_logs")->insert($insert_info);
            if ($ret) {
                Db::commit();
                InviteRule::buyCdkey($userId, $coin_symbol, $amount);
                $this->success("购买激活码成功");
            } else {
                Db::rollback();
                $this->error("购买激活码失败,请稍后重试#2");
            }
        } else {
            Db::rollback();
            $this->error("余额更新失败,请稍后重试");
        }
    }

    public function input()
    {
        $userId = $this->getUserId();

        $validate = new Validate([
            'keys'     => 'require',
        ]);

        $validate->message([
            'keys.require'  => '激活码必须填写',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        $keys = $data['keys'];

        Db::startTrans();

        $amount = 0;
        $coin_symbol = 'USDT';

        $find_cdkey = Db::name("cdkey")->where(array('status' => 1, 'selled' => 0, 'keys' => $keys))->find();
        if (!$find_cdkey) {
            Db::rollback();
            $this->error("激活码不存在或者已经被领取");
        }
        $update_info = array('selled' => 1, 'sell_time' => time(), 'uid' => $userId, 'username' => $this->user['mobile'] ? $this->user['mobile'] : $this->user['user_email'], 'price' => $amount, 'coin_symbol' => $coin_symbol);
        $update = Db::name("cdkey")->where('id', $find_cdkey['id'])->update($update_info);
        if (!$update) {
            Db::rollback();
            $this->error("领取激活码失败,请稍后重试#1");
        }
        $insert_info = array('keys' =>  $find_cdkey['keys'], 'ctime' => time(), 'uid' => $userId, 'used' => 0, 'qrobot_id' => 0);
        $ret = Db::name("cdkey_logs")->insert($insert_info);
        if ($ret) {
            Db::commit();
            $this->success("领取激活码成功");
        } else {
            Db::rollback();
            $this->error("领取激活码失败,请稍后重试#2");
        }
    }
}
